// pages/group_buy/group_buy.js

//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
      //组件tab_bar中的“首页”和“我的”
      currentid1: "未点击首页",
      currentid2: "点击我的",
      unpaid_info:[],
      bill_info: [],
      navbar: ['未支付', '全部'],
      currentTab: 0,
      currentContent: '未支付',
      pdrink: 0,
      pkit: 0,
      pball: 0,
  },

  navbarTap: function(e){
    console.log(e)
    if (e.currentTarget.dataset.idx) {
      this.setData({
        currentTab: e.currentTarget.dataset.idx,
        currentContent: '全部'
      })
    }
    if (!e.currentTarget.dataset.idx) {
      this.setData({
        currentTab: e.currentTarget.dataset.idx,
        currentContent: '未支付'
      })
    }
    console.log(this.data.currentContent)
  },

  pay_bill:function(e){
    //与服务器交互---支付接口
    wx.login({
      success: res => {
        // code 用于获取openID的条件之一
        // var code = res.code;
        var openId = wx.getStorageSync('openId')
        var crsNo = getApp().globalData.unpaid_info.bill_id     //订单号
        var react_pay = getApp().globalData.unpaid_info.goods_price * getApp().globalData.unpaid_info.usetime - getApp().globalData.unpaid_info.use_coupon * getApp().globalData.unpaid_info.coupon_price     //获取实际支付金额
        wx.request({
          url: getApp().globalData.server + '/index.php/Home/Pay/make_order',
          method: "POST",
          data: {
            openid: openId,
            data_total: react_pay,
            goods_type: getApp().globalData.unpaid_info.goods_type,
            crsNo: crsNo
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded' // 默认值
          },
          success: function (res) {  //后端返回的数据
            var data = res.data;
            console.log(data);
            console.log(data["timeStamp"]);
            wx.requestPayment({
              timeStamp: data['timeStamp'],
              nonceStr: data['nonceStr'],
              package: data['package'],
              signType: data['signType'],
              paySign: data['paySign'],
              success: function (res) {
                //支付成功后调用修改订单支付状态接口
                wx.request({
                  url: getApp().globalData.server + '/index.php/Home/QiuBao/modify_bill_state',
                  data:{
                    bill_id: getApp().globalData.unpaid_info.bill_id
                  },
                  header: {
                    'content-type': "application/x-www-form-urlencoded"
                  },
                  method: 'POST',
                  dataType: 'json',
                  success:function(res){
                    console.log(res)
                    if(res.data.error_code != 0){
                      wx.showModal({
                        title:'哎呀~',
                        content:'出错了呢！' + res.data.msg,
                        success(res){
                          if(res.confirm){
                            console.log('用户点击确定')
                          }else if(res.cancel){
                            console.log('用户点击取消')
                          }
                        }
                      })
                    }else if(res.data.error_code == 0){
                      // console.log(res.data.data)
                      console.log("订单支付成功！")
                    }
                  },
                  fail:function(res){
                    wx.showModal({
                      title:'哎呀~~',
                      content:'网络不在状态呢！',
                      success:function(res){
                        if (res.confirm) {
                          console.log("用户点击确定")
                        } else if (res.cancel) {
                          console.log("用户点击取消")
                        }
                      }
                    })
                  },
                  complete:function(res){
                    wx.hideLoading({
                      success: (res) => {},
                    })
                  }
                })
                wx.showModal({
                  title: '支付成功',
                  content: '',
                  showCancel: false,
                  success (res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                      wx.reLaunch({
                        url: '/pages/group_buy/group_buy',
                      })
                    }
                  }
                })
              },
              fail: function (res) {
                console.log("小程序这边调起支付失败啦")
                console.log(res);
              }
            })
          }
        });
      }
    })
   
  },

  //用户点击再来一单时跳转至Home首页
  again2Home:function(e){
    wx.reLaunch({
      url: '/pages/Home/Home',
    })
  },

    //利用自定义顶部导航tab_bar组件实现首页和我的页面的跳转
    tapfun1:function(event){
      console.log(event.currentTarget.id)
      // if (event.currentTarget.id == '点击首页'){
      //   this.setData({
      //     currentid1: "点击首页",
      //     currentid2: "未点击我的"
      //   })
      //   wx.reLaunch({
      //     url: '/pages/Home/Home',
      //   })
      // }
      // if (event.currentTarget.id == '未点击我的'){
      //   this.setData({
      //     currentid1: "未点击首页",
      //     currentid2: "点击我的"
      //   })
      //   wx.reLaunch({
      //     url: '/pages/group_buy/group_buy',
      //   })
      // }
      if (event.currentTarget.id == '未点击首页'){
        this.setData({
          currentid1: "点击首页",
          currentid2: "未点击我的"
        })
        wx.reLaunch({
          url: '/pages/Home/Home',
        })
      }
      // if (event.currentTarget.id == '点击我的'){
      //   this.setData({
      //     currentid1: "未点击首页",
      //     currentid2: "点击我的"
      //   })
      //   wx.reLaunch({
      //     url: '/pages/group_buy/group_buy',
      //   })
      // }
      console.log(this.data.currentid1)
      console.log(this.data.currentid2)
    },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(this.data.userInfo)
    // console.log(app.globalData.userInfo)
    //获得用户信息
    if (app.globalData.userInfo) {
      console.log(app.globalData.userInfo)
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true,
        unpaid_info: app.globalData.unpaid_info
      })
    } else {
      app.globalData.userInfo = wx.getStorageSync("userInfo");
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true,
        unpaid_info: app.globalData.unpaid_info
      })
    }
    console.log(this.data.unpaid_info)
    var that = this

    //与服务器交互---Find_Bill账单信息查找接口（半完成，没有联系用户id,计划在PHP端用post传输用户id），并把账单信息存储至全局变量中
    wx.request({
      url: getApp().globalData.server + '/index.php/Home/QiuBao/Find_Bill',
      data:{
        user_id: wx.getStorageSync('openId'), 
      },
      method:"POST",
      header: {
        'content-type': "application/x-www-form-urlencoded"
      },
      method: 'POST',
      dataType: 'json',
      success:function(res){
        // console.log(res)
        if(res.data.error_code != 0){
          wx.showModal({
            title:'哎呀~',
            content:'出错了呢！' + res.data.msg,
            success(res){
              if(res.confirm){
                console.log('用户点击确定')
              }else if(res.cancel){
                console.log('用户点击取消')
              }
            }
          })
        }else if(res.data.error_code == 0){
          console.log("成功请求到find_bill")
          that.setData({
            bill_info: res.data.data
          })
          for (let i = 0; i < res.data.data.length; i++) {
            if (res.data.data[i].bill_status=="未支付") {
              getApp().globalData.unpaid = true
              getApp().globalData.unpaid_info = res.data.data[i]
              that.setData({
                unpaid_info: getApp().globalData.unpaid_info
              })
              //判断是否实付为0，如果为0的话直接自动调用修改订单支付状态接口将订单状态改为已支付
              var react_pay = getApp().globalData.unpaid_info.goods_price * getApp().globalData.unpaid_info.usetime - getApp().globalData.unpaid_info.use_coupon * getApp().globalData.unpaid_info.coupon_price     //获取实际支付金额
              console.log(react_pay)
              if (react_pay==0) {
                  wx.request({
                    url: getApp().globalData.server + '/index.php/Home/QiuBao/modify_bill_state',
                    data:{
                      bill_id: getApp().globalData.unpaid_info.bill_id
                    },
                    header: {
                      'content-type': "application/x-www-form-urlencoded"
                    },
                    method: 'POST',
                    dataType: 'json',
                    success:function(res){
                      console.log(res)
                      if(res.data.error_code != 0){
                        wx.showModal({
                          title:'哎呀~',
                          content:'出错了呢！' + res.data.msg,
                          success(res){
                            if(res.confirm){
                              console.log('用户点击确定')
                            }else if(res.cancel){
                              console.log('用户点击取消')
                            }
                          }
                        })
                      }else if(res.data.error_code == 0){
                        // console.log(res.data.data)
                        console.log("订单支付成功！")
                      }
                    },
                    fail:function(res){
                      wx.showModal({
                        title:'哎呀~~',
                        content:'网络不在状态呢！',
                        success:function(res){
                          if (res.confirm) {
                            console.log("用户点击确定")
                          } else if (res.cancel) {
                            console.log("用户点击取消")
                          }
                        }
                      })
                    },
                    complete:function(res){
                      wx.hideLoading({
                        success: (res) => {},
                      })
                    }
                  })
                  getApp().globalData.unpaid = false
                  getApp().globalData.unpaid_info = []
                  wx.reLaunch({
                    url: '/pages/group_buy/group_buy',
                  })
              }
              break
            }
            getApp().globalData.unpaid = false
            getApp().globalData.unpaid_info = []
          } 
          console.log("我是：" + getApp().globalData.unpaid)
          console.log(getApp().globalData.unpaid_info)
          // console.log(that.data.bill_info[0].coupon_price)
            //当有未支付订单时，先判断是否为有usetime即是否有使用，没有的话就直接删除订单，有的话就请求使用优惠卷接口
          if (getApp().globalData.unpaid && (getApp().globalData.unpaid_info.coupon_name=="无")) {
            console.log("查询到有未支付的订单，开始请求使用优惠卷接口...");
            if (getApp().globalData.unpaid_info.usetime!="0") {
              //通过未支付订单订单号，完善订单
              wx.request({
                url: getApp().globalData.server + '/index.php/Home/QiuBao/Complete_order',
                data:{
                  user_id: wx.getStorageSync('openId'), 
                  bill_id: getApp().globalData.unpaid_info.bill_id
                },
                header: {
                  'content-type': "application/x-www-form-urlencoded"
                },
                method: 'POST',
                dataType: 'json',
                success:function(res){
                  var there = that
                  // console.log(res)
                  if(res.data.error_code != 0){
                    wx.showToast({
                      title: '阿西吧~' + res.data.msg,//提示文字
                      duration:2000,//显示时长
                      mask:true,//是否显示透明蒙层，防止触摸穿透，默认：false  
                      // icon:'', //图标，支持"success"、"loading"  
                      success:function(){ },//接口调用成功
                      fail: function () { },  //接口调用失败的回调函数  
                      complete: function () { } //接口调用结束的回调函数  
                  })
                  }else if(res.data.error_code == 0){
                      console.log(res.data)
                      getApp().globalData.unpaid = false
                      getApp().globalData.unpaid_info = []
                    }                  
                    // console.log(getApp().globalData.unpaid)
                    // console.log(getApp().globalData.unpaid_info)
                    wx.reLaunch({
                      url: '/pages/group_buy/group_buy',
                    })
                    // console.log(that.data.bill_info[0].coupon_price)
                },
                fail:function(res){
                  wx.showModal({
                    title:'哎呀~~',
                    content:'网络不在状态呢！',
                    success:function(res){
                      if (res.confirm) {
                        console.log("用户点击确定")
                      } else if (res.cancel) {
                        console.log("用户点击取消")
                      }
                    }
                  })
                },
                complete:function(res){
                  wx.hideLoading({
                    success: (res) => {},
                  })
                }
              })
            } else {
              wx.request({
                url: getApp().globalData.server + '/index.php/Home/QiuBao/delete_bill',
                data:{
                  bill_id: getApp().globalData.unpaid_info.bill_id
                },
                header: {
                  'content-type': "application/x-www-form-urlencoded"
                },
                method: 'POST',
                dataType: 'json',
                success:function(res){
                  var there = that
                  // console.log(res)
                  if(res.data.error_code != 0){
                    wx.showToast({
                      title: '阿西吧~' + res.data.msg,//提示文字
                      duration:2000,//显示时长
                      mask:true,//是否显示透明蒙层，防止触摸穿透，默认：false  
                      // icon:'', //图标，支持"success"、"loading"  
                      success:function(){ },//接口调用成功
                      fail: function () { },  //接口调用失败的回调函数  
                      complete: function () { } //接口调用结束的回调函数  
                  })
                  }else if(res.data.error_code == 0){
                      console.log(res.data)
                      getApp().globalData.unpaid = false
                      getApp().globalData.unpaid_info = []
                    } 
                    console.log(getApp().globalData.unpaid)
                    console.log(getApp().globalData.unpaid_info)
                    wx.reLaunch({
                      url: '/pages/group_buy/group_buy',
                    })
                    // console.log(that.data.bill_info[0].coupon_price)
                },
                fail:function(res){
                  wx.showModal({
                    title:'哎呀~~',
                    content:'网络不在状态呢！',
                    success:function(res){
                      if (res.confirm) {
                        console.log("用户点击确定")
                      } else if (res.cancel) {
                        console.log("用户点击取消")
                      }
                    }
                  })
                },
                complete:function(res){
                  wx.hideLoading({
                    success: (res) => {},
                  })
                }
              })
            }
          }
        }
      },
      fail:function(res){
        wx.showModal({
          title:'哎呀~~',
          content:'网络不在状态呢！',
          success:function(res){
            if (res.confirm) {
              console.log("用户点击确定")
            } else if (res.cancel) {
              console.log("用户点击取消")
            }
          }
        })
      },
      complete:function(res){
        wx.hideLoading({
          success: (res) => {},
        })
      }
    })

    //与服务器交互---查找用户使用设备信息接口（半完成，没有联系用户id,计划在PHP端用post传输用户id）
    wx.request({
      url: getApp().globalData.server + '/index.php/Home/QiuBao/Find_UserInfo',
      data:{
        user_id: wx.getStorageSync('openId'), 
      },
      header: {
        'content-type': "application/x-www-form-urlencoded"
      },
      method: 'POST',
      dataType: 'json',
      success:function(res){
        // console.log(res)
        if(res.data.error_code != 0){
          wx.showModal({
            title:'哎呀~',
            content:'出错了呢！' + res.data.msg,
            success(res){
              if(res.confirm){
                console.log('用户点击确定')
              }else if(res.cancel){
                console.log('用户点击取消')
              }
            }
          })
        }else if(res.data.error_code == 0){
          // console.log(res.data.data)
          that.setData({
            pdrink:res.data.data[0][0].drink_time,
            pball:res.data.data[1][0].basketball_time,
            pkit:res.data.data[2][0].kit_time
          })
        }
      },
      fail:function(res){
        wx.showModal({
          title:'哎呀~~',
          content:'网络不在状态呢！',
          success:function(res){
            if (res.confirm) {
              console.log("用户点击确定")
            } else if (res.cancel) {
              console.log("用户点击取消")
            }
          }
        })
      },
      complete:function(res){
        wx.hideLoading({
          success: (res) => {},
        })
      }
    })

    console.log(111111111111111111111111111111)
    console.log(getApp().globalData.unpaid)
    console.log(!getApp().globalData.unpaid_info.coupon_name)
    console.log(getApp().globalData.unpaid_info.coupon_name)
    console.log(111111111111111111111111111111)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log("开始进行onshow-生命周期函数--监听页面显示")

    console.log("我的账单界面onshow调用完成！")
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})